package com.happy.study.util;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 自定义缓存工具类
 * 使用CurrentHashMap线程安全类
 * 并设置缓存有效期，需要线程监控
 */
public class MapCacheUtil {


    private static long time = 5 * 60 * 1000;

    /**
     * 创建一个单例的线程安全类
     */
    private static Map<String, Object> cache = null;


    /**
     * 私有构造函数，保证单例
     */
    private MapCacheUtil () {
    }

    /**
     * 单例模式构建一个全局共享的内存级别缓存
     */

    private static Map<String, Object> getCacheMap () {
        if ( cache == null ) {
            cache = new ConcurrentHashMap<String, Object> ();
        }
        return cache;
    }


    /**
     * 设置数据缓存，并设置有效期
     *
     * @param key
     * @param obj
     */
    public static void setCache ( String key, Object obj ) {
        getCacheMap ().put ( key + "verification", obj );
        getCacheMap ().put ( key + "timer", System.currentTimeMillis () );
    }

    /**
     * 从缓存中取数据
     *
     * @param key
     * @return
     */
    public static Object getCache ( String key ) {
        return getCacheMap ().get ( key + "verification" );
    }

    /**
     * 删除指定缓存
     *
     * @param key
     */
    public static void removeCache ( String key ) {
        getCacheMap ().remove ( key + "verification" );
        getCacheMap ().remove ( key + "timer" );
    }


    public static void checkCache ( String key ) {
        if ( cache != null ) {
            for ( Map.Entry<String, Object> entry : cache.entrySet () ) {
                long date = (long) getCacheMap ().get ( key + "timer" ); // 存的时间
                if ( date + time <= System.currentTimeMillis () ) {
                    // 过期了
                    removeCache ( key );
                }
            }
        }
    }

}
